#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include<semaphore.h>

#include "menu.h"
#include "list.h"
#include "playcontrl.h"

Song *pnow = NULL;
int fd[2];
sem_t sem;

int mainmenu()
{
	int x;
	printf("\t\t\t      Mplayer\n");
	printf("\t\t\t********************\n");
	printf("\t\t\t     1.歌单操作\n");
	printf("\t\t\t     2.播放控制\n");
	printf("\t\t\t     3.音量控制\n");
	printf("\t\t\t     0.退出\n");
	printf("\t\t\t********************\n");
	printf("please select:\n");
	scanf("%d",&x);
	while(x<0 || x>4)
	{
		printf("input error,again:\n");
		scanf("%d",&x);
	}
	return x;
}


int main()
{
	//int x,loop = 1;

	pthread_t tid1,tid2,tid3;
	sem_init(&sem,0,1);

	if(access("pipe",F_OK) != 0)
	{
		mkfifo("pipe",0666);
	}
	
	if(pipe(fd) < 0)    //记得初始化
	{
		perror("pipe error\n");
		return 0;
	}
	fcntl(fd[0], F_SETFL, O_NONBLOCK); //无名管道设为非阻塞

	pid_t pid = fork();
	if(pid < 0)
	{
		perror("fork fail\n");
		return 1;
	}
	else if(pid == 0)
	{
		close(fd[0]);
		dup2(fd[1],1);
		Song *head = read_song();
		pnow = head;
		char buf[100] = {0};
		strcpy(buf,head->path);
		execl("/usr/bin/mplayer","mplayer","-quiet","-slave","-idle","-input","file=pipe",buf,NULL);
	}
	else
	{
		atexit(exitsong);

		close(fd[1]);
		sleep(1);
		pthread_create(&tid1,NULL,getcmd_thread,NULL);
	
		pthread_create(&tid2,NULL,sndfd_thread,NULL);

		pthread_create(&tid3,NULL,readfd_thread,NULL);

		int a = pthread_join(tid1,NULL);
		printf("a=%d\n",a);
		int b = pthread_join(tid2,NULL);
		printf("b=%d\n",b);
		int c = pthread_join(tid3,NULL);
		printf("c=%d\n",c);
	}
}
